package com.tyk.bookstore.back.system.valid.validator;

import com.tyk.bookstore.back.common.core.valid.util.ValidUtil;
import com.tyk.bookstore.back.system.valid.annotation.PermissionFieldValid;
import com.tyk.bookstore.back.system.valid.constant.PermissionFieldValidConstant;
import com.tyk.bookstore.back.system.valid.type.PermissionFieldValidType;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;

public class PermissionFieldConstraintValidator implements ConstraintValidator<PermissionFieldValid, Object> {
    private PermissionFieldValidType[] types;

    @Override
    public void initialize(PermissionFieldValid constraintAnnotation) {
        types = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null) {
            return true;
        }

        for (PermissionFieldValidType type : types) {
            switch (type) {
                case CODE, CODE_LIKE -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String)value, PermissionFieldValidConstant.CODE_MIN_LENGTH, PermissionFieldValidConstant.CODE_MAX_LENGTH, PermissionFieldValidConstant.CODE_PATTERN);
                    }
                }
                case NAME, NAME_LIKE, GROUP_NAME -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value, PermissionFieldValidConstant.NAME_MIN_LENGTH, PermissionFieldValidConstant.NAME_MAX_LENGTH, PermissionFieldValidConstant.NAME_PATTERN);
                    }
                }
                case DESCRIPTION -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value, PermissionFieldValidConstant.DESCRIPTION_MIN_LENGTH, PermissionFieldValidConstant.DESCRIPTION_MAX_LENGTH);
                    }
                }
            }
        }

        throw new IllegalArgumentException("非法取值" + Arrays.toString(types) + value);
    }
}
